<?php

class Item extends MainModel implements IECartPosition {

	public static function model($className=__CLASS__){
		return parent::model($className);
	}
	
    function getId(){
        return $this->id;
    }

    function getPrice(){
        $price = $this->price;
		$price = number_format($price, 2, '.', '');
		return $price;
    }

	public function tableName(){
		return '{{item}}';
	}

	public function rules(){

		return array(
			array('show, avalible', 'in', 'range'=>array(0, 1)),
			array('title, category, manufacturer', 'required'),
			array('price, old_price', 'numerical'),
			array('rating_yes, rating_no', 'numerical', 'integerOnly'=>true),
			array('show, avalible', 'length', 'max'=>1),
			array('manufacturer, category, created, updated, viewcount', 'length', 'max'=>10),
			array('title, permalink, alt_title, alt_keywords', 'length', 'max'=>255),
			array('description, alt_description', 'safe'),
			array('id, show, avalible, manufacturer, category, title, permalink, price, old_price, description, alt_title, alt_keywords, alt_description, created, updated, viewcount, rating_yes, rating_no', 'safe', 'on'=>'search'),
		);
	}

	public function relations(){
		return array(
			'category' => array(self::BELONGS_TO, 'Category', 'category'),
			'manufacturer' => array(self::BELONGS_TO, 'Manufacturer', 'manufacturer'),
			'features' => array(self::MANY_MANY, 'Feature', '{{item_feature}}(item, feature)'),
			'images' => array(self::MANY_MANY, 'File', '{{content_file}}(item, file)'),
		);
	}

	public function attributeLabels(){
		return array(
			'id' => 'id',
			'show' => 'Отображать',
			'avalible' => 'Доступен для заказа',
			'manufacturer' => 'Производитель',
			'category' => 'Категория',
			'title' => 'Наименование',
			'permalink' => 'Ссылка',
			'price' => 'Цена',
			'old_price' => 'Старая цена',
			'description' => 'Описание',
			'alt_title' => 'Альт. наименование',
			'alt_keywords' => 'Альт. ключевые слова',
			'alt_description' => 'Альт. описание',
			'created' => 'Создан',
			'updated' => 'Обновлен',
			'viewcount' => 'Кол-во просмотров',
			'rating_yes' => 'Понравилось',
			'rating_no' => 'Не понравилось',
		);
	}

	public function search(){

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id,true);
		$criteria->compare('show',$this->show,true);
		$criteria->compare('avalible',$this->avalible,true);
		$criteria->compare('manufacturer',$this->manufacturer,true);
		$criteria->compare('category',$this->category,true);
		$criteria->compare('title',$this->title,true);
		$criteria->compare('permalink',$this->permalink,true);
		$criteria->compare('price',$this->price);
		$criteria->compare('old_price',$this->old_price);
		$criteria->compare('description',$this->description,true);
		$criteria->compare('alt_title',$this->alt_title,true);
		$criteria->compare('alt_keywords',$this->alt_keywords,true);
		$criteria->compare('alt_description',$this->alt_description,true);
		$criteria->compare('created',$this->created,true);
		$criteria->compare('updated',$this->updated,true);
		$criteria->compare('viewcount',$this->viewcount,true);
		$criteria->compare('rating_yes',$this->rating_yes);
		$criteria->compare('rating_no',$this->rating_no);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

	public function afterSave() {
		if (!$this->isNewRecord) {
			$this->dbConnection->createCommand('DELETE FROM {{item_feature}} WHERE item='.$this->id)->execute();
		}
		if(count($this->features) > 0){
			foreach ($this->features as $feature) {
				if ((Feature::model()->findByPk($feature)) !== null) {
					$this->dbConnection->createCommand('INSERT INTO {{item_feature}} (item, feature) VALUES ('.$this->id.','.$feature.')')->execute();
				}
			}
		}
	}

	public function afterFind(){

		$category = $this->category;
		$category = Category::model()->findByPk($category);
		
		if($category){
			if($category->price_factor AND $category->price_factor != 0 AND $category->price_factor != ''){
				$factor = $category->price_factor;
			}else{
				$factor = 1;
			}
			if($category->price_add){
				$add = $category->price_add;
			}else{
				$add = 0;
			}
			$this->price = (($this->price)*$factor)+$add;
		}
		
		$this->price 			= round($this->price, 2);
		$this->price 			= number_format($this->price, 2, '.', '');
		
		if(!$this->old_price){
			$this->old_price = $this->price*1.1;
		}
		$this->old_price 		= round($this->old_price, 2);
		$this->old_price 		= number_format($this->old_price, 2, '.', '');
		
	}
	
	function price_max(){
		$this->getDbCriteria()->mergeWith(array(
			'order'=>'price DESC',
			'limit'=>1,
		));
		return $this;
	}

	function price_min(){
		$this->getDbCriteria()->mergeWith(array(
			'order'=>'price ASC',
			'limit'=>1,
		));
		return $this;
	}
	
	//количество позиций в корзине
	function countInCart(){
		$position = Yii::app()->shoppingCart->itemAt($this->id);
		if($position){
			$quantity = $position->getQuantity();
		}else{
			$quantity = 0;
		}
		return $quantity;
	}
}